import dayjs from 'dayjs'
import type { MockEndpoint, RouteParams } from '../types'
import { mockExecutions } from '../data/executions'

export const taskEndpoints: Record<string, MockEndpoint> = {
  '/api/tasks': {
    GET: () => ({
      code: 0,
      msg: '操作成功',
      data: [
        {
          id: '1',
          name: '示例任务1',
          command: 'echo "Hello World"',
          schedule: '0 0 0 12 * * *',
          enabled: true,
          nextRun: '2024-01-16T12:00:00Z',
          lastRun: '2024-01-15T12:00:00Z',
          description: '每天中午12点执行',
          running: true,
          executionId: 'exec_001'
        },
        {
          id: '2',
          name: '示例任务2',
          command: 'node backup.js',
          schedule: '0 0 0 2 * * *',
          enabled: false,
          description: '每天凌晨2点执行备份',
          running: false
        },
        {
          id: '3',
          name: '数据同步任务',
          command: 'python sync_data.py',
          schedule: '0 */30 * * * *',
          enabled: true,
          nextRun: '2024-01-15T14:30:00Z',
          lastRun: '2024-01-15T14:00:00Z',
          description: '每30分钟同步一次数据',
          running: true,
          executionId: 'exec_002'
        },
        {
          id: '4',
          name: '日志清理任务',
          command: 'sh cleanup_logs.sh',
          schedule: '0 0 1 * * *',
          enabled: true,
          nextRun: '2024-01-16T01:00:00Z',
          lastRun: '2024-01-15T01:00:00Z',
          description: '每天凌晨1点清理日志',
          running: false
        }
      ]
    }),
    POST: (_url: string, _params?: RouteParams, data?: any) => ({
      code: 0,
      msg: '任务创建成功',
      data: {
        id: String(Date.now()),
        ...data,
        nextRun: dayjs().add(1, 'day').format(),
        running: false
      }
    }),
    PUT: (_url: string, _params?: RouteParams, data?: any) => ({
      code: 0,
      msg: '任务更新成功',
      data: {
        ...data,
        nextRun: dayjs().add(1, 'day').format()
      }
    }),
    DELETE: () => ({
      code: 0,
      msg: '任务删除成功'
    })
  },
  '/api/tasks/:id/toggle': {
    POST: (_url: string, _params?: RouteParams, data?: any) => ({
      code: 0,
      msg: data?.enabled ? '任务已启用' : '任务已禁用',
      data: {
        ...data,
        nextRun: data?.enabled ? dayjs().add(1, 'day').format() : null
      }
    })
  },
  '/api/tasks/:id/execute': {
    POST: () => {
      const executionId = Math.random().toString(36).substring(2)
      const startTime = new Date().toISOString()
      
      // 模拟异步执行过程
      setTimeout(() => {
        const success = Math.random() > 0.2
        const duration = Math.floor(Math.random() * 2000) + 1000
        const endTime = new Date(new Date(startTime).getTime() + duration).toISOString()
        
        mockExecutions.set(executionId, {
          id: executionId,
          startTime,
          endTime,
          duration,
          status: success ? 'success' : 'error',
          output: [
            '正在初始化...',
            '正在执行命令...',
            success ? '命令执行成功！' : '命令执行失败：权限不足',
            `总耗时：${(duration / 1000).toFixed(2)}秒`,
            success ? '退出码：0' : '退出码：1'
          ].join('\n')
        })
      }, 3000)
      
      // 初始状态
      mockExecutions.set(executionId, {
        id: executionId,
        startTime,
        duration: 0,
        status: 'running',
        output: '正在初始化...\n'
      })
      
      return {
        code: 0,
        msg: '任务执行成功',
        data: {
          success: true,
          executionId
        }
      }
    }
  },
  '/api/tasks/:id/stop': {
    POST: () => {
      // 查找正在运行的执行记录
      for (const [key, execution] of mockExecutions.entries()) {
        if (execution.status === 'running') {
          const endTime = new Date().toISOString()
          const duration = new Date().getTime() - new Date(execution.startTime).getTime()
          
          // 更新执行记录为已停止
          mockExecutions.set(key, {
            ...execution,
            endTime,
            duration,
            status: 'error',
            output: execution.output + '\n任务已被用户手动停止\n退出码：130'
          })
          break
        }
      }
      
      return {
        code: 0,
        msg: '任务停止成功',
        data: {
          success: true,
          message: '任务停止成功'
        }
      }
    }
  },
  '/api/tasks/executions/:id': {
    GET: (_url: string, params?: RouteParams) => {
      const execution = mockExecutions.get(params?.id || '')
      if (execution) {
        return {
          code: 0,
          msg: '操作成功',
          data: execution
        }
      }
      return {
        code: 404,
        msg: '执行记录不存在'
      }
    }
  }
} 